package com.lovol.surfaceviewdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 标准 SurfaceView 的用法
 * 绘制正选曲线
 */
public class SurfaceViewSinFun extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private static final String TAG = "SurfaceViewSinFun";

    //帧速率
    private static final long FRAME_RATE = 30;

    private Thread mThread;
    private SurfaceHolder mSurfaceHolder;
    //绘图的Canvas
    private Canvas mCanvas;
    //子线程标志位
    private volatile boolean mIsDrawing;
    private int x = 0, y = 0;
    private Paint mPaint;
    private Path mPath;

    public SurfaceViewSinFun(Context context) {
        this(context, null);
    }

    public SurfaceViewSinFun(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SurfaceViewSinFun(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(5);
        mPath = new Path();
        //路径起始点(0, 100)
        mPath.moveTo(0, 100);
        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
        mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
        setFocusable(true);
        setKeepScreenOn(true);
        setFocusableInTouchMode(true);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surfaceCreated: ");
        mIsDrawing = true;
        mThread= new Thread(this);
        mThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i(TAG, "surfaceChanged: width=" + width + " height=" + height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "surfaceDestroyed: ");
        // 结束线程
        boolean retry = true;
        while (retry) {
            try {
                mIsDrawing = false;
                mThread.join();
                retry = false;
            } catch (InterruptedException e) {
                //e.printStackTrace();
                // 如果线程无法正常结束，则继续重试
            }
        }
        Log.i(TAG, "surfaceDestroyed: after ");
    }

    @Override
    public void run() {
        System.out.println("SurfaceViewSinFun.run 我是在子线程中打印的日志");
        while (mIsDrawing) {
            drawSomething();
            x += 1;
            y = (int) (100 * Math.sin(2 * x * Math.PI / 180) + 400);
            //加入新的坐标点
            mPath.lineTo(x, y);
        }
    }

    /**
     * 核心方法 1：
     *
     * 使用 SurfaceHolder 的 lockCanvas() 方法获取一个 Canvas 对象，
     * 并在同步块中来绘制游戏界面，最后使用 SurfaceHolder 的 unlockCanvasAndPost() 方法释放 Canvas 对象并提交绘制结果。
     * 在绘制完成后，我们需要计算绘制所需的时间，并休眠一段时间以维持一定的帧率。
     */
    private void drawSomething() {
        long startTime = System.currentTimeMillis();
        drawView();

        //需要计算绘制所需的时间，并休眠一段时间以维持一定的帧率
        long endTime = System.currentTimeMillis();
        long timeDiff = endTime - startTime;
        long sleepTime = FRAME_RATE - timeDiff;
        try {
            if (sleepTime > 0) {
                //System.out.println("SurfaceViewSinFun.drawSomething sleepTime=" + sleepTime);
                Thread.sleep(sleepTime);
                //Thread.sleep(20*1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 核心方法 2
     */
    private void drawView() {
        try {
            //获取一个 Canvas 对象，
            mCanvas = mSurfaceHolder.lockCanvas();
            synchronized (mSurfaceHolder) {
                if (mCanvas != null) {
                    //绘制背景
                    mCanvas.drawColor(Color.WHITE);
                    //绘制路径
                    mCanvas.drawPath(mPath, mPaint);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mCanvas != null) {
                //释放canvas对象并提交画布
                mSurfaceHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }


}
